var inquirer = require('inquirer');
const http = require('http');
const { options } = require('./mergeRequest.option');

const { gitlabHost, targetProjectId, PRIVATETOKEN } = options;

/**
 * 发起gitlab的merge request，利用gitlab的api接口实现。
 * 需要在配置文件中配置gitlab的地址、推送目标的项目的id，个人的PRIVATETOKEN，推动到的分支。
 * 当前分支发起merge request。
 * @param {*} source_branch 
 * @param {*} lastMessage 
 * @param {*} _targetBranch 
 */
function mergeRequest(targetProjectId, source_branch, lastMessage, _targetBranch) {
  inquirer
    .prompt([{ type: 'confirm', name: 'mergeRequest', message: `mergeRequest到【${_targetBranch}】分支吗？` }])
    .then(answers => answers.mergeRequest)
    .then(mergeRequest => {
      if (mergeRequest === true) {
        const data = {
          id: targetProjectId,
          source_branch,
          target_branch: _targetBranch,
          title: lastMessage
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'PRIVATE-TOKEN': PRIVATETOKEN
          },
        };
        const url = `${gitlabHost}api/v4/projects/${targetProjectId}/merge_requests`;
        console.log(`请求gitlab api：${url}`);

        const req = http.request(url, options, res => {
          if (res.statusCode === 200 || res.statusCode === 201) {
            console.warn('搞定😎');
          } else {
            console.error(`请求遇到问题:${res.statusCode}`);
          }
        });
        req.on('error', e => {
          console.error(`请求遇到问题: ${e.message}`, e);
        });

        // post请求时，将数据写入请求body。
        req.write(JSON.stringify(data));
        req.end();
      }
    });
}

var targetBranch = {
  type: 'list',
  name: 'targetBranch',
  message: '向哪个分支发起merge request？',
  choices: []
};
// 选择项目
var targetProject = {
  type: 'list',
  name: 'targetProject',
  message: '选择项目',
  choices: []
};

/**
 * target_branch为配置参数，如果是多个，则需要用户选择一个分支
 */
exports.mergeRequest = function (source_branch, lastMessage) {
  // 获取远程的分支
  var exec = require('child_process').exec;

  // TODO 获取当前目录的package.json中的name字段，根据这个项目名，匹配配置文件中的项目名，从而拿到project_id。

  exec('git branch -r', function (err, stdout) {
    // 获取当前分支的名字
    var branchArray = stdout.split('\n');
    branchArray = branchArray.map(item => item.replace(/\s+/g, ''));

    targetProject.choices = targetProjectId.map(({ name, id }) => ({ name, value: id }));
    targetBranch.choices = branchArray.map((branch) => ({ name: branch, value: branch.replace(/origin\//, '') }));
    // 选中目标分支
    inquirer
      .prompt([targetProject, targetBranch])
      .then(({ targetProject, targetBranch }) => {
        mergeRequest(targetProject, source_branch, lastMessage, targetBranch);
      });
  });
};
